//
//  HWNewCircleListViewController.swift
//  HWanGame
//
//  Created by Apple on 2024/8/13.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView
import ZLPhotoBrowser
import Kingfisher

class HWNewCircleListViewController: HWBaseViewController {

    let httpManager = HWGameCircleHttpManager()
    var releaseButton:UIButton!
    var modelArr = [HWGameCircleModel]()
    var isLoginGoBack = false
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(HWDynamicListCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 306*widthScale
        return tableView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
        loadData()

        addRefresh()
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if isLoginGoBack == true {
            loadData()
            isLoginGoBack = false
        }
        
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        releaseButton.isHidden = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        releaseButton.isHidden = true
    }
}

extension HWNewCircleListViewController {
    
    private func initUI() -> Void {
        navigationView.isHidden = true
        view.backgroundColor = .clear
        
        view.backgroundColor = "#F7F8FA".toColor
        
        view.addSubview(tableView)

        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }

        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        releaseButton = UIButton(type: .custom)
        releaseButton.setImage(UIImage(named: "Push"), for: .normal)
        releaseButton.addTarget(self, action: #selector(releaseButtonClick(_:)), for: .touchUpInside)
        currentWindow?.rootViewController?.view.addSubview(releaseButton)
        let panGesture = UIPanGestureRecognizer(target: self, action:#selector(dragAction(gesture:)))
        releaseButton.addGestureRecognizer(panGesture)
        
        
        let config = ZLPhotoConfiguration.default()
        
        config.languageType = .chineseSimplified
    }
    
    private func initFrame() -> Void {
        tableView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalTo(0)
        }
        
        releaseButton.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.width.equalTo(88*widthScale)
            make.height.equalTo(88*widthScale)
            make.bottom.equalTo(-CGFloat.tabBar_height)
        }
    }
}

extension HWNewCircleListViewController {
    
    func loadData() -> Void {
           
        self.httpManager.getGameCircleList { models in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.modelArr.removeAll()
                self.modelArr = models
            }
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
    
    func addRefresh() -> () {
        
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        self.tableView.mj_footer?.endRefreshing()
        self.httpManager.getGameCircleListFooter { models in
            self.tableView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.modelArr.append(contentsOf: models)
            }
            self.tableView.reloadData()
        } failure: { error in

            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
}


//MARK: - UITableViewDelegate, UITableViewDataSource
extension HWNewCircleListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.modelArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        //动态
        let cell = tableView.dequeueReusableCell(withIdentifier: "HWDynamicListCell", for: indexPath) as! HWDynamicListCell
        cell.circleModel = self.modelArr[indexPath.row]
        cell.zanButtonClick = { id in
            self.httpManager.setTakeALookZan(type: "0", id: id) { message in
                self.loadData()
            } failure: { error in
                
            }
        }
        cell.jumpToDetail = { mod in
            let detailController = HWTakeALookDetailController()
            detailController.model = mod
            detailController.deteleBlock = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(detailController, animated: true)
        }
        cell.didSelectImage = { index,images in
            self.selectImage(index: index, images: images)
        }
        cell.didSelectVideo = { url in
            self.selectVideo(url: url)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let detailController = HWTakeALookDetailController()
        detailController.model = modelArr[indexPath.row]
        detailController.deteleBlock = {
            self.loadNewData()
        }
        detailController.likeBlock = {
            self.loadNewData()
        }
        self.navigationController?.pushViewController(detailController, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
}


//MARK: action
extension HWNewCircleListViewController {
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    @objc private func dragAction(gesture: UIPanGestureRecognizer) {
        
        // 移动状态
        let moveState = gesture.state
        switch moveState {
        case .began:
            break
        case .changed:
            // floatBtn 获取移动轨迹
            let point = gesture.translation(in: self.view)
            self.releaseButton.center = CGPoint(x: self.releaseButton.center.x + point.x, y: self.releaseButton.center.y + point.y)
            break
        case .ended:
            // floatBtn 移动结束吸边
            let point = gesture.translation(in: self.view)
            var newPoint = CGPoint(x: self.releaseButton.center.x +  point.x, y: self.releaseButton.center.y + point.y)
            if newPoint.x < screenWidth / 2.0 {
                newPoint.x = self.releaseButton.bounds.width/2 + 17*widthScale
            } else {
                newPoint.x = screenWidth - self.releaseButton.bounds.width/2 - 17*widthScale
            }
            if newPoint.y <= self.releaseButton.bounds.height/2 + 17*widthScale + navigationView.bounds.height{
                newPoint.y = self.releaseButton.bounds.height/2 + 17*widthScale + navigationView.bounds.height
            } else if newPoint.y >= self.view.bounds.height - self.releaseButton.bounds.height/2 - 17*widthScale {
                newPoint.y = self.view.bounds.height - self.releaseButton.bounds.height/2 - 17*widthScale
            }
            // 0.5秒 吸边动画
            UIView.animate(withDuration: 0.5) {
                self.releaseButton.center = newPoint
            }
            break
        default:
            break
        }
        // 重置 panGesture
        gesture.setTranslation(.zero, in: self.view)
    }
    
    @objc private func releaseButtonClick(_:UIButton) -> Void {
        if HWLocallyStoredData.getLoginUserID().count>0{
//            let releaseController = HWTakeALookReleaseController()
//            releaseController.releaseCallBack = {
//                self.loadNewData()
//            }
//            self.navigationController?.pushViewController(releaseController, animated: true)
            let pushButton = HWPushDynamicViewController()
            self.present(pushButton, animated: true)
        }else{
            let loginController = HWLoginController()
            self.navigationController?.pushViewController(loginController, animated: true)
            loginController.goBack = {
                self.isLoginGoBack = true
            }
        }
        
    }
    
}

extension HWNewCircleListViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
